<template>
    <div>
        <el-scrollbar height="500px">
            <el-table 
                :data="displayData" 
                border 
                style="width: 100%"
                ref="tableRef"
                :max-height="500"
            >
                <slot name="id"></slot>
                <el-table-column prop="order" label="订单号" show-overflow-tooltip/>
                <el-table-column prop="branches" label="所属分店" show-overflow-tooltip width="120">
                    <template #default="scope">
                        <assign-shop
                            v-model:shopName="scope.row.branches"
                            :memberId="scope.row.order"
                            type="order"
                        />
                    </template>
                </el-table-column>
                <el-table-column prop="customerName" label="客户姓名" show-overflow-tooltip/>
                <el-table-column prop="phone" label="联系电话" show-overflow-tooltip/>
                <el-table-column prop="address" label="客户地址" show-overflow-tooltip/>
                <el-table-column prop="customerAttribute" label="客户属性"  show-overflow-tooltip/>
                <el-table-column prop="price" label="价格"  show-overflow-tooltip/>
                <el-table-column prop="customerType" label="客户类型"  show-overflow-tooltip/>
                <el-table-column prop="serviceType" label="服务类型" show-overflow-tooltip/>
                <el-table-column prop="expectedTime" label="期望时间" show-overflow-tooltip/>
                <el-table-column prop="arrivalTime" label="上门时间" show-overflow-tooltip width="120">
                    <template #default="scope">
                      <span>{{ scope.row.arrivalTime }}</span>
                      <el-button type="primary" @click="emitter.emit('selectTime', scope.row)"  v-show="!scope.row.arrivalTime" >分配时间</el-button>
                    </template>
                </el-table-column>
                
                <el-table-column label="服务员工" width="120">
                  <template #default="scope">
                    <span>{{ scope.row.serviceStaff }}</span>
                    <el-button type="primary" @click="emitter.emit('selectHuman', scope.row)"  v-show="!scope.row.serviceStaff">分配员工</el-button>
                  </template>
                </el-table-column>
                <el-table-column label="是否收款" width="120">
                  <template #default="scope">
                    <span v-show="scope.row.payStatus">已收款: {{ scope.row.price }}元</span>
                    <el-button type="primary" @click="confirmMoney(scope.row)" v-show="!scope.row.payStatus">确认收款</el-button>
                  </template>
                </el-table-column>
                <slot name="operate"></slot>
            </el-table>
        </el-scrollbar>
        <el-dialog
            v-model="shopDialogVisible"
            title="分配店铺"
            width="30%"
        >
            <el-select v-model="selectedShopId" placeholder="请选择店铺" style="width: 100%">
                <el-option
                    v-for="item in shopList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
            </el-select>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="shopDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmAssignShop">
                        确认
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="table">
import useMoney from '@/hooks/useMoney'
import { toRefs, ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { emitter } from '@/utils/emitter';
import { useStaffStore } from '@/stores/useStaffStore';
import { ElMessage } from 'element-plus';
import instance from '@/api';
import AssignShop from '@/components/AssignShop.vue';

interface TableDataType {
    order: string;
    branches: string;
    customerName: string;
    phone: string;
    address: string;
    customerAttribute: string;
    price: number;
    customerType: string;
    serviceType: string;
    expectedTime: string;
    arrivalTime: string;
    serviceStaff: string;
    payStatus: number;
}

const props = defineProps<{
    tableData: TableDataType[]
}>();

const { tableData } = toRefs(props)
const { confirmMoney } = useMoney()

// 分页相关
const pageSize = 20; // 每页显示数量
const currentPage = ref(1);
const loading = ref(false);
const hasMore = ref(true);
const tableRef = ref();
const isInitialLoad = ref(true);
const scrollPosition = ref(0);

// 计算当前显示的数据
const displayData = computed(() => {
    if (!tableData.value) return [];
    return tableData.value.slice(0, currentPage.value * pageSize);
});

// 保存滚动位置
const saveScrollPosition = () => {
    const scrollbar = tableRef.value?.$el.querySelector('.el-scrollbar__wrap');
    if (scrollbar) {
        scrollPosition.value = scrollbar.scrollTop;
    }
};

// 恢复滚动位置
const restoreScrollPosition = () => {
    const scrollbar = tableRef.value?.$el.querySelector('.el-scrollbar__wrap');
    if (scrollbar) {
        scrollbar.scrollTop = scrollPosition.value;
    }
};

// 监听数据变化，保持滚动位置
watch(() => tableData.value, () => {
    saveScrollPosition();
    nextTick(() => {
        restoreScrollPosition();
    });
}, { deep: true });

// 处理滚动事件
const handleScroll = async () => {
    // 跳过初始加载检查
    if (isInitialLoad.value) {
        isInitialLoad.value = false;
        return;
    }

    const scrollbar = tableRef.value?.$el.querySelector('.el-scrollbar__wrap');
    if (!scrollbar) return;
    
    const { scrollHeight, scrollTop, clientHeight } = scrollbar;
    
    // 当滚动到距离底部20px时触发加载
    if (scrollHeight - scrollTop - clientHeight < 20 && !loading.value && hasMore.value) {
        loading.value = true;
        saveScrollPosition();
        
        // 检查是否还有更多数据
        const nextPage = currentPage.value + 1;
        const nextPageData = tableData.value?.slice((nextPage - 1) * pageSize, nextPage * pageSize);
        
        if (nextPageData && nextPageData.length > 0) {
            // 模拟加载延迟，让用户体验更好
            await new Promise(resolve => setTimeout(resolve, 300));
            currentPage.value = nextPage;
            nextTick(() => {
                restoreScrollPosition();
            });
        } else {
            hasMore.value = false;
        }
        
        loading.value = false;

    }
};

// 监听分配员工和时间的事件
onMounted(() => {
    const scrollbar = tableRef.value?.$el.querySelector('.el-scrollbar__wrap');
    if (scrollbar) {
        scrollbar.addEventListener('scroll', handleScroll);
    }

    // 监听分配员工事件
    emitter.on('selectHuman', (row) => {
        saveScrollPosition();
    });

    // 监听分配时间事件
    emitter.on('selectTime', (row) => {
        saveScrollPosition();
    });
    staffStore.fetchShopList();
});

onUnmounted(() => {
    const scrollbar = tableRef.value?.$el.querySelector('.el-scrollbar__wrap');
    if (scrollbar) {
        scrollbar.removeEventListener('scroll', handleScroll);
    }
    
    // 移除事件监听
    emitter.off('selectHuman');
    emitter.off('selectTime');
});

const staffStore = useStaffStore();
const shopDialogVisible = ref(false);
const currentRow = ref<any>(null);
const selectedShopId = ref<number>();

// 获取店铺列表
const shopList = computed(() => {
    return staffStore.shopList.map((shop: { id: number; shop_name: string }) => ({
        value: shop.id,
        label: shop.shop_name
    }));
});

// 处理分配店铺
const handleAssignShop = (row: any) => {
    currentRow.value = row;
    selectedShopId.value = undefined;
    shopDialogVisible.value = true;
};

// 确认分配店铺
const confirmAssignShop = async () => {
    if (!selectedShopId.value) {
        ElMessage.warning('请选择店铺');
        return;
    }
    try {
        const resp = await instance.put(`/api/order/assignShop?orderId=${currentRow.value.order}&shopId=${selectedShopId.value}`);
        if (resp.status === 200) {
            ElMessage.success('分配店铺成功');
            // 更新当前行的店铺信息
            const shop = shopList.value.find((s: { value: number; label: string }) => s.value === selectedShopId.value);
            if (shop) {
                currentRow.value.branches = shop.label;
            }
            shopDialogVisible.value = false;
        }
    } catch (error) {
        ElMessage.error('分配店铺失败');
    }
};
</script>

<style scoped>
.el-table {
    --el-table-row-height: 50px;
}
</style>